﻿using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using System;
using System.IO;
using System.Reflection;
using System.Text;
using Device = SharpDX.Direct3D11.Device;
using Resource = SharpDX.Direct3D11.Resource;

namespace MikadoShooter
{
    public static partial class GameHelper
    {
        public static void EffectStringTexture(Effect effect, DXWindow dXWindow, string text)
        {
            if (String.IsNullOrEmpty(text))
                return;

            using (Texture2D tex = Resource.FromMemory<Texture2D>(dXWindow.Device, RenderString(text, dXWindow.RenderForm)))
            {
                using (ShaderResourceView shaderView = new ShaderResourceView(dXWindow.Device, tex, new ShaderResourceViewDescription
                {
                    Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                    Texture2D = new ShaderResourceViewDescription.Texture2DResource
                    {
                        MipLevels = 1
                    }
                }))
                {
                    effect.GetVariableByName("tex2D").AsShaderResource().SetResource(shaderView);
                }
            }
        }


        public static Effect EffectInit(Device device,string fileName)
        {
            Effect effect = LoadFile(device, fileName);

            using (InputLayout input = new InputLayout
            (
                device,
                ShaderSignature.GetInputSignature(effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature),
                new[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, Vector4.SizeInBytes, 0)
                }
            ))
            {
                device.ImmediateContext.InputAssembler.InputLayout = input;
            }

            return effect;
        }

        public static Effect LoadFile(Device device, string fileName)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MikadoShooter.Context." + fileName);

            try
            {
                if (stream == null)
                    throw new ApplicationException("Error loading effect file!");

                using (StreamReader reader = new StreamReader(stream))
                {
                    //Shadercompiler need ASCII files NOT UTF
                    return new Effect(device, ShaderBytecode.Compile(Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.UTF8.GetBytes(reader.ReadToEnd())), "fx_5_0"));
                }
            }
            finally
            {
                if (stream != null) 
                    stream.Close();
            }
        }
    }
}